package eee.xiang.cloud_learning.service;

import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Comparator;
import java.util.Date;
import java.util.concurrent.*;

/**
 * @author x-yin
 * @Date 2019/10/8
 */

@Service
public class ScheduleThreadService {

    private static ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(2);
    ScheduledFuture<?> scheduledFuture = null;
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:MM:ss");

    public void startSchedule(){
        scheduledFuture = scheduledThreadPoolExecutor.scheduleWithFixedDelay(() -> {
            System.out.println(111111);
            System.out.println(222222);
            System.out.println(333333);
            System.out.println(888888);
        }, 2, 2, TimeUnit.SECONDS);
    }

    public void stopSchedule(){
        scheduledFuture.cancel(true);
    }

    public void distinctTest(){

        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(3);
        Runnable task0 = new Runnable() {
            public void run() {
                String name = Thread.currentThread().getName();
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(name + "周期" + sdf.format(new Date()));
            }
        };
        Runnable task1 = new Runnable() {
            public void run() {
                String name = Thread.currentThread().getName();
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(name + "延迟" + sdf.format(new Date()));
            }
        };

        scheduledExecutorService.scheduleAtFixedRate(task0, 1, 2,TimeUnit.SECONDS);
        scheduledExecutorService.scheduleWithFixedDelay(task1, 1, 2,TimeUnit.SECONDS);
    }

    public static void main(String[] args) {
        new ScheduleThreadService().distinctTest();
    }


}
